<template>
  <div class="container">
    <div class="app-container">
      <el-avatar src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" />
      <el-button type="danger" size="mini" @click="showDialog=true">角色管理</el-button>
      <el-table :data="tableData" border="" style="margin:20px 0" size="mini">
        <el-table-column prop="name" label="角色" width="100">
          <template #default="{row}">
            <span v-if="!row.isEdit">{{ row.name }}</span>
            <!-- 绑定临时数据 临时数据随便你折腾  我有备份 真正的数据在row.name -->
            <el-input v-else v-model="row.temp.name" size="mini" />
          </template>
        </el-table-column>

        <!-- state是1 显示 启用 否则未启用 -->
        <!-- <el-table-column prop="state" label="是否启用" width="100" /> -->
        <el-table-column label="是否启用" width="100">
          <template #default="{row}">
            <span v-if="!row.isEdit">{{ row.state === 1 ? '启用' : '未启用' }}</span>
            <el-switch v-else v-model="row.temp.state" :active-value="1" :inactive-value="0" size="mini" />
          </template>
        </el-table-column>

        <el-table-column prop="description" label="描述">
          <template #default="{row}">
            <span v-if="!row.isEdit">{{ row.description }}</span>
            <el-input v-else v-model="row.temp.description" type="textarea" size="mini" />
          </template>
        </el-table-column>

        <el-table-column label="操作">
          <!-- 通过默认插槽指定结构 -->
          <!--  -->
          <!-- 文字按钮 -->
          <template #default="{row}">
            <!-- {{ row }} -->
            <!-- obj是这个组件的作者在封装el-table-column组件时，传递给默认插槽的参数 -->
            <div v-if="!row.isEdit">
              <el-button type="text">分配权限</el-button>
              <el-button type="text" @click="row.isEdit=true">编辑</el-button>
              <el-popconfirm title="你确定吗" @onConfirm="del(row.id)">
                <template #reference>
                  <el-button type="text">删除</el-button>
                </template>
              </el-popconfirm>
            </div>
            <div v-else>
              <el-button size="mini" type="primary" @click="edit(row)">确定</el-button>
              <el-button size="mini" @click="cancelEdit(row)">取消</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!--
        pagination 分页组件
          current-page 当前页码
          page-sizes  可供选择的 每页显示多少条
          page-size 每页显示多少条
          total   总记录数
          layout  你希望这个组件有多少个功能
          @size-change="handleSizeChange" 更新每页条数数据
          @current-change="handleCurrentChange" 改变页码时会触发的
      -->
      <el-pagination
        :current-page="page"
        :page-sizes="[3,4,5,6]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        small=""
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
      <!-- 新增角色对话框 -->
      <el-dialog title="新增角色" :visible.sync="showDialog" width="500px" @close="clear">
        <template #title>新增</template>

        <el-form ref="xx" :model="formObj" :rules="rules" label-width="100px" size="mini">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="formObj.name" />
          </el-form-item>
          <el-form-item label="启用">
            <!-- <el-input></el-input> -->
            <el-switch
              v-model="formObj.state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="formObj.description" type="textarea" />
          </el-form-item>
        </el-form>

        <template #footer>
          <el-button size="mini" type="primary" @click="add">确定</el-button>
          <el-button size="mini" @click="clear">取消</el-button>
        </template>
      </el-dialog>
    </div>

  </div>
</template>
<script>
import { addRole, deleteRole, getRoleList, updateRole } from '@/api/role'

export default {
  name: 'Role',
  data() {
    return {
      tableData: [],
      total: 0,
      pageSize: 5,
      page: 1,
      showDialog: false,
      // 表单对象数据
      formObj: {
        name: '',
        description: '',
        state: 1
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
  // 获取数据
    async getList() {
      const { rows, total } = await getRoleList(this.page, this.pageSize)
      this.tableData = rows
      this.total = total
      // 因为每一个数据都要有属于自己的是否处于编辑状态，所以在数据返回的时候需要添加一个数据，因为是临时加入的所以没有响应式，所以尤大准备了一个方法this.$set(数据，待添加的字段名，初始值)
      this.tableData.forEach((item) => {
        this.$set(item, 'isEdit', false)
        // 绑定一个临时的数据，用于绑定
        this.$set(item, 'temp', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
    },
    // 改变页面会触发的 val是当前点击的页码
    handleCurrentChange(val) {
      this.page = val
      this.getList()
    },
    // 更新每页条数数据
    handleSizeChange(val) {
      this.pageSize = val
      this.page = 1// 重置页码
      this.getList()
    },
    // 用于添加编辑
    add() {
      this.$refs.xx.validate(async(isOk) => {
        if (isOk) {
        // 发请求（封装接口）——关闭清空对话框——提示——重新请求重新渲染
          await addRole(this.formObj)
          this.$message.success('添加成功')
          // 清空和关闭
          this.clear()

          // 重新发请求渲染
          this.getList()
        }
      })
    },
    // 清空和关闭对话框
    clear() {
      this.showDialog = false
      this.$refs.xx.resetFields()
      this.formObj = {
        name: '',
        description: '',
        state: 1
      }
    },
    cancelEdit(row) {
      row.isEdit = false
      row.temp.name = row.name
      row.temp.state = row.state
      row.temp.description = row.description
    },
    async edit(row) {
      await updateRole({
        ...row.temp,
        id: row.id
      })
      this.$message.success('修改成功')
      this.getList()
    },
    async del(id) {
      await deleteRole(id)// 请求后端
      this.$message.success('删除成功')
      if (this.tableData.length === 1 && this.page > 1) this.page--

      this.getList()
    }
  }

}
</script>
